package com.shushan.mixedexam.speaking;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechError;
import com.shushan.base.BaseFragment;
import com.shushan.base.Constants;
import com.shushan.mixedexam.BaseExamFragment;
import com.shushan.mixedexam.MixedExamActivity;
import com.shushan.mixedexam.OnAnswerSelectListener;
import com.shushan.mixedexam.bean.MutiExerciseBean;
import com.shushan.shushanbao.R;
import com.shushan.ui.RoundProgressBar;
import com.shushan.util.AudioRecordUtil;
import com.shushan.util.DownloadUtil;
import com.shushan.util.ExamAudioPlayUtil;
import com.shushan.util.SpeechEvaluatorUtil;
import com.shushan.util.ToolUtils;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @ClassName: SpeakingExamFragment
 * @Desciption: //口语试题fragment
 * @author: zhangshihao
 * @date: 2018-06-20
 */
public class SpeakingExamFragment extends BaseExamFragment implements View.OnClickListener {

    private static final String TAG = SpeakingExamFragment.class.getSimpleName();

    private View contentView;
    private RelativeLayout rlRecord;
    private RelativeLayout rlScore;
    private ImageView ivScore;
    private TextView tvScore;
    private RoundProgressBar pbRecord;
    private ImageView ivMic;
    private ImageView ivTrumpet;
    private TextView tvReadContent;
    private TextView tvReadHint;

    private boolean onRecord = false;
    private boolean alreadyScore = false;
    private String recordPath = AudioRecordUtil.getInstance().getOutFileName();
    private AnimationDrawable audioPlayAnim;
    private String evaStr;
    private float costTime;//句子大概需要几秒读完：单位毫秒
    private EvaluatorListener mEvaluatorListener = new EvaluatorListener() {
        @Override
        public void onVolumeChanged(int i, byte[] bytes) {
        }

        @Override
        public void onBeginOfSpeech() {
            Log.d(TAG, "onBeginOfSpeech...");
        }

        @Override
        public void onEndOfSpeech() {
            Log.d(TAG, "onEndOfSpeech...");
        }

        @Override
        public void onResult(EvaluatorResult result, boolean isLast) {
            Log.d(TAG,"onResult : isLast == "+isLast);
            if (isLast) {
                StringBuilder builder = new StringBuilder();
                builder.append(result.getResultString());
                showScore(parseXml(builder.toString()));
                if((getActivity()) != null) {
                    ((MixedExamActivity)getActivity()).enableNextBtn();
                }
            }
        }

        @Override
        public void onError(SpeechError speechError) {
            Log.d(TAG,"onError ...");
            rlScore.setVisibility(View.VISIBLE);
            tvScore.setText(String.valueOf(0) + "分");
            ivScore.setImageResource(R.drawable.ic_low_score);
            exerciseBean.my_option = "0";
            if (onAnswerSelectListener != null && !isMutiTimesScore) {
                isMutiTimesScore = true;
                onAnswerSelectListener.onAnswerSelect(examIndex, false);
                if((getActivity()) != null) {
                    ((MixedExamActivity)getActivity()).enableNextBtn();
                }
            }
            if(speechError != null) {
                showToast("speechError:"+ speechError.getErrorCode() + "," + speechError.getErrorDescription());
            } else {
                Log.d(TAG, "evaluator over");
            }
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    };
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if ((int) msg.obj == 0) {
                ivMic.setImageResource(R.drawable.ic_mic);
            } else if ((int) msg.obj == 1) {
                ivMic.setImageResource(R.drawable.ic_play_record);
            }
        }
    };
    private boolean isOnlyDisplay = false;
    private int examIndex = 0;
    private MutiExerciseBean exerciseBean;
    private OnAnswerSelectListener onAnswerSelectListener;
    private boolean isMutiTimesScore = false;//是否同一个题多次打分

    public static SpeakingExamFragment newInstance(boolean isOnlyDisplay, int examIndex, MutiExerciseBean exerciseBean) {
        SpeakingExamFragment examFragment = new SpeakingExamFragment();
        examFragment.setOnlyDisplay(isOnlyDisplay);
        examFragment.setExamIndex(examIndex);
        examFragment.setExerciseBean(exerciseBean);

        return examFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate : init SpeechEvaluatorUtil");
        SpeechEvaluatorUtil.init(getContext());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.i(TAG,"onCreateView...");
        if(contentView == null) {
            contentView = inflater.inflate(R.layout.fragment_speaking_exercise, null, false);

            initView(contentView);

            initData();
        }
        return contentView;
    }

    private void initView(View view) {
        rlRecord = view.findViewById(R.id.rl_record);
        rlRecord.setOnClickListener(this);
        pbRecord = view.findViewById(R.id.pb_record);
        ivMic = view.findViewById(R.id.iv_mic);
        rlScore = view.findViewById(R.id.rl_score);
        ivScore = view.findViewById(R.id.iv_score);
        tvScore = view.findViewById(R.id.tv_score);
        ivTrumpet = view.findViewById(R.id.iv_trumpet);
        ivTrumpet.setOnClickListener(this);
        ivTrumpet.setImageResource(R.drawable.anim_audio_play);
        audioPlayAnim = (AnimationDrawable) ivTrumpet.getDrawable();
        tvReadContent = view.findViewById(R.id.tv_read_content);
        tvReadHint = view.findViewById(R.id.tv_read_hint);
    }

    private void initData(){
        if(exerciseBean == null){
            return;
        }

        if(isOnlyDisplay){
            rlRecord.setVisibility(View.GONE);
            tvReadHint.setVisibility(View.GONE);
            rlScore.setVisibility(View.VISIBLE);
            int hundredScore = ToolUtils.getSpeakingScore(exerciseBean);
            tvScore.setText(hundredScore+ "分");
            if (hundredScore >= 70) {
                ivScore.setImageResource(R.drawable.ic_high_score);
            } else {
                ivScore.setImageResource(R.drawable.ic_low_score);
            }
        }
        evaStr = exerciseBean.exercises_content;
        costTime = exerciseBean.voice_time;
        if(costTime == 0){
            costTime = 3000;
        }
        tvReadContent.setText(exerciseBean.exercises_content);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_record:
                onRecord = true;
                ExamAudioPlayUtil.stop();
                if(alreadyScore){
                    LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(new Intent(Constants.SPEAKING_EXAM_ALREAD_SCORE_ACTION));
                }
                rlRecord.setOnClickListener(null);
                AudioRecordUtil.getInstance().startRecord();
                AudioRecordUtil.getInstance().recordData();
                pbRecord.countBack(pbRecord, (int) costTime);
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        AudioRecordUtil.getInstance().stopRecord();
                        AudioRecordUtil.getInstance().convertWaveFile();
                        mHandler.sendMessage(mHandler.obtainMessage(0, 1));
                        SpeechEvaluatorUtil.startEva(AudioRecordUtil.getAudioData(recordPath),evaStr,mEvaluatorListener);
                        ExamAudioPlayUtil.playAudio(pbRecord, recordPath, new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                mHandler.sendMessage(mHandler.obtainMessage(0, 0));
                                rlRecord.setOnClickListener(SpeakingExamFragment.this);
                                alreadyScore = true;
                                onRecord = false;
                            }
                        });
                    }
                }, (int) costTime);
                break;
            case R.id.iv_trumpet:
                if(!onRecord) {
                    ExamAudioPlayUtil.playAudio(DownloadUtil.getSpeakingExamAudioPath(exerciseBean.outline_detail_id, exerciseBean.id), audioPlayAnim);
                }
                break;
        }
    }

    private void showScore(float score) {
        rlScore.setVisibility(View.VISIBLE);
        int hundredScore = (int) (score * 20);
        tvScore.setText(String.valueOf(hundredScore) + "分");
        if (hundredScore >= 70) {
            ivScore.setImageResource(R.drawable.ic_high_score);
        } else {
            ivScore.setImageResource(R.drawable.ic_low_score);
        }
        if(!isOnlyDisplay) {
            exerciseBean.my_option = getAnswerScore(hundredScore);
            if (onAnswerSelectListener != null && !isMutiTimesScore) {
                isMutiTimesScore = true;
                onAnswerSelectListener.onAnswerSelect(examIndex, hundredScore >= 70 ? true : false);
            }
        }
    }

    private String getAnswerScore(int score){
        String answerScore = "";
        answerScore = String.valueOf((int)(((float)score/100)*exerciseBean.score));

        return answerScore;
    }

    private float parseXml(String xmlStr) {
        float totalScore = 0f;
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlStr));
            int eventType = xmlPullParser.getEventType();
            String value;
            while (eventType != xmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        if ("total_score".equals(nodeName)) {
                            value = xmlPullParser.getAttributeValue(0);
                            totalScore = Float.parseFloat(value);
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                eventType = xmlPullParser.next();
            }
        } catch (XmlPullParserException xppe) {
            Log.i(TAG, xppe.toString());
        } catch (IOException ioe) {
            Log.i(TAG, ioe.toString());
        }
        return totalScore;
    }


    public boolean isOnlyDisplay() {
        return isOnlyDisplay;
    }

    public void setOnlyDisplay(boolean onlyDisplay) {
        isOnlyDisplay = onlyDisplay;
    }

    public int getExamIndex() {
        return examIndex;
    }

    public void setExamIndex(int examIndex) {
        this.examIndex = examIndex;
    }

    public MutiExerciseBean getExerciseBean() {
        return exerciseBean;
    }

    public void setExerciseBean(MutiExerciseBean exerciseBean) {
        this.exerciseBean = exerciseBean;
    }

    public OnAnswerSelectListener getOnAnswerSelectListener() {
        return onAnswerSelectListener;
    }

    public void setOnAnswerSelectListener(OnAnswerSelectListener onAnswerSelectListener) {
        this.onAnswerSelectListener = onAnswerSelectListener;
    }

    public AnimationDrawable getAudioPlayAnim() {
        return audioPlayAnim;
    }

    public String getAudioPath(MutiExerciseBean bean){
        if(bean == null){
            return "";
        }
        return DownloadUtil.getSpeakingExamAudioPath(bean.outline_detail_id, bean.id);
    }

}
